package handler

import (
	"net/http"
	"golang.org/x/crypto/bcrypt"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"plastic-company/internal/middleware"
	"plastic-company/internal/model"
)

var db *gorm.DB

// SetDB 设置数据库连接
func SetDB(database *gorm.DB) {
	db = database
}

// Register 注册处理
func Register(c *gin.Context) {
	var registerData struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&registerData); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误: " + err.Error(),
		})
		return
	}

	// 检查用户名是否已存在
	var existingAdmin model.Admin
	result := db.Where("username = ?", registerData.Username).First(&existingAdmin)
	if result.Error == nil {
		c.JSON(http.StatusConflict, model.APIResponse{
			Success: false,
			Message: "用户名已存在",
		})
		return
	}

	// 加密密码
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(registerData.Password), bcrypt.DefaultCost)
	if err != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "密码加密失败",
		})
		return
	}

	// 创建新用户
	newAdmin := model.Admin{
		Username: registerData.Username,
		Password: string(hashedPassword),
	}

	result = db.Create(&newAdmin)
	if result.Error != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "创建用户失败",
		})
		return
	}

	c.JSON(http.StatusCreated, model.APIResponse{
		Success: true,
		Message: "注册成功",
		Data: gin.H{
			"id":       newAdmin.ID,
			"username": newAdmin.Username,
		},
	})
}

// Login 登录处理
func Login(c *gin.Context) {
	var loginData struct {
		Username string `json:"username" binding:"required"`
		Password string `json:"password" binding:"required"`
	}

	if err := c.ShouldBindJSON(&loginData); err != nil {
		c.JSON(http.StatusBadRequest, model.APIResponse{
			Success: false,
			Message: "请求参数错误",
		})
		return
	}

	// 从数据库查找用户
	var admin model.Admin
	result := db.Where("username = ?", loginData.Username).First(&admin)
	if result.Error != nil {
		c.JSON(http.StatusUnauthorized, model.APIResponse{
			Success: false,
			Message: "用户名或密码错误",
		})
		return
	}

	// 验证密码
	err := bcrypt.CompareHashAndPassword([]byte(admin.Password), []byte(loginData.Password))
	if err != nil {
		c.JSON(http.StatusUnauthorized, model.APIResponse{
			Success: false,
			Message: "用户名或密码错误",
		})
		return
	}

	// 生成JWT令牌
	token, err := middleware.GenerateToken(admin.ID, admin.Username)
	if err != nil {
		c.JSON(http.StatusInternalServerError, model.APIResponse{
			Success: false,
			Message: "生成令牌失败",
		})
		return
	}

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "登录成功",
		Data: gin.H{
			"token": token,
			"user": gin.H{
				"id":       admin.ID,
				"username":  admin.Username,
			},
		},
	})
}

// Logout 退出登录处理
func Logout(c *gin.Context) {
	// 实际项目中可能需要将令牌加入黑名单
	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Message: "退出成功",
	})
}

// Me 获取当前用户信息
func Me(c *gin.Context) {
	userID, exists := c.Get("userID")
	if !exists {
		c.JSON(http.StatusUnauthorized, model.APIResponse{
			Success: false,
			Message: "未登录",
		})
		return
	}

	username, _ := c.Get("username")

	c.JSON(http.StatusOK, model.APIResponse{
		Success: true,
		Data: gin.H{
			"id":       userID,
			"username":  username,
		},
	})
}